package org.gl;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpVersion;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpProtocolParams;
import org.gl.utils.AndroidUtil;
import org.gl.utils.DebugUtil;
import org.gl.utils.ExceptionHandler;
import org.gl.utils.lg;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.view.WindowManager;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.map.MKEvent;
import com.chanceit.ssss.activity.R;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

/**
 * 創建�??MyApplication类，管理打开的应用程�?当程序�?出时finish Activity call by：InstantActicity
 * 
 * @author gl
 * 
 */
@SuppressLint("NewApi")
public class GlobalVariable extends Application {

	private static List<Activity> activityList = new LinkedList<Activity>();
	private DetectSdcard in;
	public static Application applicationContext;
	public static GlobalVariable application;
	public static String Server_IP = "";
	public static String Server_PORT = "80";
	private static String interfaceURLPrefix = "http://" + Server_IP + ":"
			+ Server_PORT + "/api.action?v=&cmd=";
	/**
	 * 针对4S点的车标图片
	 */
	public static String URL_image = "";
//	public static String URL_image = "/res/logo/org/";
	/**
	 * 上传接口 遵循HTTP File upload
	 */
	public static String URL_image_upload = "http://www.chanceit.cn:8081/fileload/servlet/Uploadify";
	// public static String URL_image_upload =
	// "http://192.168.0.195:7777/fileload/servlet/Uploadify";
	/**
	 * 4S的图片服务器目录
	 */
	public static String URL_image_down = "http://www.chanceit.cn:8081/fileload/";
	// public static String URL_image_down =
	// "http://192.168.0.195:7777/fileload/";

	public static JSONObject UserInfo = null;
	public static int role = 0;;
	/**
	 * 屏幕宽（单位为像素）
	 */
	public static int disPlay_w = 0;

	public static String getInterfaceURLPrefix() {
		interfaceURLPrefix = "http://" + Server_IP + ":" + Server_PORT
				+ "/api.action?v=&cmd=";
		URL_image = "http://" + Server_IP + ":" + Server_PORT
				+ "/res/logo/small/";///res/logo/org/
		lg.i("application", "interfaceURLPrefix" + interfaceURLPrefix);
		return interfaceURLPrefix;
	}

	/**
	 * 屏幕高（单位为像素）
	 */
	public static int disPlay_h = 0;
	/**
	 * 没有外置存储卡则�?cacheDir:/data/data/com.zyfkj.rnbs/files/"否则为："/sdcard/ rnbs/"
	 */
	public static String AppFileSystemDir;
	public static DefaultHttpClient DefaultHttpClient;
	public Intent intent;

	@SuppressWarnings("deprecation")
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		applicationContext = this;
		application = this;
		intent = new Intent();
		updateIp();
		getInterfaceURLPrefix();
		initFileSystem();
		WindowManager wm = ((WindowManager) applicationContext
				.getSystemService(WINDOW_SERVICE));
		disPlay_h = wm.getDefaultDisplay().getHeight();
		disPlay_w = wm.getDefaultDisplay().getWidth();

		DefaultHttpClient = initHttpClient();
		// 注册文件系统变动观察�?
		registFileSystemObser();
		// regist uncaughtExceptoin handler
		if (!DebugUtil.isDebug) {
			ExceptionHandler.getInstance().init(applicationContext);
		}

		TelephonyManager manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		String imei = manager.getDeviceId();
		String imsi = manager.getSubscriberId();
		// System.out.println("imei"+imei);
		// System.out.println("imsi"+imsi);
		// System.out.println("Build.MODEL"+Build.MODEL);

		initImageLoader(getApplicationContext());

		initEngineManager(this);
	}

	/**
	 * 获取最新的服务器IP
	 */
	public void updateIp() {
		Server_IP = AndroidUtil.getServerIPConfig();
		Server_PORT = AndroidUtil.getServerPortConfig();
		lg.i("application", "Server host:" + Server_IP + Server_PORT);
	}

	DefaultHttpClient initHttpClient() {
		final int DEFAULT_SOCKET_BUFFER_SIZE = 8 * 1024; // 8KB
		// final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
		// final String ENCODING_GZIP = "gzip";

		int maxConnections = 10; // http请求最大并发连接数
		int socketTimeout = 10 * 1000; // 超时时间，默认10秒
		// int maxRetries = 5;// 错误尝试次数，错误异常表请在RetryHandler添加
		// int httpThreadCount = 3;// http线程池数量
		// String charset = "utf-8";
		BasicHttpParams httpParams = new BasicHttpParams();

		ConnManagerParams.setTimeout(httpParams, socketTimeout);
		ConnManagerParams.setMaxConnectionsPerRoute(httpParams,
				new ConnPerRouteBean(maxConnections));
		ConnManagerParams.setMaxTotalConnections(httpParams, 10);

		HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
		HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
		HttpConnectionParams.setTcpNoDelay(httpParams, true);
		HttpConnectionParams.setSocketBufferSize(httpParams,
				DEFAULT_SOCKET_BUFFER_SIZE);
		HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setUseExpectContinue(httpParams, false);
		// HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler()
		// {
		//
		// @Override
		// public boolean retryRequest(IOException arg0, int arg1, HttpContext
		// arg2) {
		// // retry a max of 5 times
		// if (arg1 >= 3) {
		// return false;
		// }
		// if (arg0 instanceof
		// ch.boye.httpclientandroidlib.NoHttpResponseException) {
		// return true;
		// } else if (arg0 instanceof
		// ch.boye.httpclientandroidlib.client.ClientProtocolException) {
		// return true;
		// }
		// return false;
		// }
		// };
		// sHttpClient.setHttpRequestRetryHandler(retryHandler);
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		schemeRegistry.register(new Scheme("https", SSLSocketFactory
				.getSocketFactory(), 443));
		ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(
				httpParams, schemeRegistry);

		return new DefaultHttpClient(cm, httpParams);
	}

	/**
	 * /注册文件系统变动观察�?
	 */
	private void registFileSystemObser() {
		in = new DetectSdcard();
		IntentFilter intentf = new IntentFilter();
		intentf.addAction(Intent.ACTION_MEDIA_MOUNTED);// 已挂载SDCARD
		intentf.addAction(Intent.ACTION_MEDIA_UNMOUNTED);// 未挂载SDCARD
		intentf.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);// 恶意拔SDCARD
		intentf.addAction(Intent.ACTION_MEDIA_SHARED);// 被挂起SDCARD
		intentf.addAction(Intent.ACTION_MEDIA_UNMOUNTABLE);// 无法挂载SDCARD
		// 隐式intent�?��加上下面这句作匹配，否则接收不到广播
		intentf.addDataScheme("file");
		registerReceiver(in, intentf);
	}

	/**
	 * 初始化文件系�?
	 */
	public void initFileSystem() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			File file = new File(Environment.getExternalStorageDirectory()
					.getAbsolutePath()
					+ File.separator
					+ "rnbs"
					+ File.separator);
			if (!file.exists()) {
				if (!file.mkdirs()) {
					lg.e(this.getClass().getSimpleName(), "外置文件存储目录创建失败");
					AppFileSystemDir = file.getAbsolutePath() + File.separator;
				} else {
					AppFileSystemDir = file.getAbsolutePath() + File.separator;
				}
				;
			} else {
				AppFileSystemDir = file.getAbsolutePath() + File.separator;
			}
		} else {
			AppFileSystemDir = getFilesDir().getAbsolutePath() + File.separator;
		}
		lg.i("Application", "文件系统当前目录:" + AppFileSystemDir);
		
	}

	/**
	 * 得到�?��当前的安全的文件存储目录,防止可能的外置存储器错误，如 sdcard被移�?
	 */
	public String getSafeCacheFileDir() {
		initFileSystem();
		return AppFileSystemDir;
	}

	// �?��sdcard是否在机器中
	public class DetectSdcard extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED)) {
				// 挂载�?..
				getSafeCacheFileDir();
			} else if (intent.getAction().equals(Intent.ACTION_MEDIA_UNMOUNTED)) {
				// 非挂�?..
				getSafeCacheFileDir();
			} else if (intent.getAction().equals(
					Intent.ACTION_MEDIA_BAD_REMOVAL)) {
				getSafeCacheFileDir();
			} else if (intent.getAction().equals(Intent.ACTION_MEDIA_SHARED)) {
				getSafeCacheFileDir();
			} else if (intent.getAction().equals(
					Intent.ACTION_MEDIA_UNMOUNTABLE)) {

				getSafeCacheFileDir();
			}
			lg.i("Application", "app file system path:" + AppFileSystemDir);
		}

	}

	/**
	 * 单例模式中获取唯�?��MyApplication实例
	 * 
	 * @return
	 */
	public static GlobalVariable getGlobalInstance() {
		if (null == application) {
			application = new GlobalVariable();
		}
		return application;

	}

	/**
	 * 添加Activity到容器中
	 * 
	 * @param activity
	 */
	public void addActivity(Activity activity) {
		activityList.add(activity);
	}

	/**
	 * 遍历�?��Activity并finish 强制结束进程
	 */
	public void exit() {
		if (in != null) {
			try {
				this.unregisterReceiver(in);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		for (Activity activity : activityList) {
			activity.finish();
		}
		/**
		 * 退出百度地图
		 */
		if (mBMapManager != null) {
			mBMapManager.destroy();
			mBMapManager = null;
		}
		System.exit(0);
	}

	public Activity getActivity(String flag) {
		for (Activity activity : activityList) {
			if (flag.equals(activity.getLocalClassName())) {
				return activity;
			}
		}
		return null;
	}

	public static boolean isFirstUseApp() {
		return AndroidUtil.isFirstUseApp();
	}
	/**
	 * 初始化图片加载器
	 * 
	 * @param context
	 */
	public static void initImageLoader(Context context) {
		// This configuration tuning is custom. You can tune every option, you
		// may tune some of them,
		// or you can create default configuration by
		// ImageLoaderConfiguration.createDefault(this);
		// method.
		DisplayImageOptions di = new DisplayImageOptions.Builder()
				// .showStubImage(R.drawable.ic_more)
				// .showImageForEmptyUri(R.drawable.ic_error)
				// .showImageOnFail(R.drawable.ic_error)
				.cacheInMemory(true).cacheOnDisc(true)
				.displayer(new RoundedBitmapDisplayer(3)).build();

		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context).threadPriority(Thread.NORM_PRIORITY)
				.denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.defaultDisplayImageOptions(di)
				// .writeDebugLogs() // Remove for release app
				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
	}

	/**
	 * for map
	 */

	public boolean m_bKeyRight = true;
	BMapManager mBMapManager = null;
	/**
	 * baidu key base debug key <br>
	 * D4:37:38:38:5A:05:1C:2B:31:EF:D8:7A:0C:13:
	 * 4E:3A:01:D7:3B:6C;com.chanceit.ssss.activity
	 * 
	 */
	public static final String strKey = "BA9c6ce369b8de1106f515776b015532";

	/*
	 * 注意：为了给用户提供更安全的服务，Android SDK自v2.1.3版本开始采用了全新的Key验证体系。
	 * 因此，当您选择使用v2.1.3及之后版本的SDK时，需要到新的Key申请页面进行全新Key的申请， 申请及配置流程请参考开发指南的对应章节
	 */

	public void initEngineManager(Context context) {
		if (mBMapManager == null) {
			mBMapManager = new BMapManager(context);
		}

		if (!mBMapManager.init(strKey, new MyGeneralListener())) {
			Toast.makeText(getInstance().getApplicationContext(),
					"BMapManager  初始化错误!", Toast.LENGTH_LONG).show();
		}
	}

	public static GlobalVariable getInstance() {
		return application;
	}

	// 常用事件监听，用来处理通常的网络错误，授权验证错误等
	static class MyGeneralListener implements MKGeneralListener {

		@Override
		public void onGetNetworkState(int iError) {
			if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
				Toast.makeText(getInstance().getApplicationContext(),
						"百度地图无法识别网络连接！", Toast.LENGTH_LONG).show();
			} else if (iError == MKEvent.ERROR_NETWORK_DATA) {
				Toast.makeText(getInstance().getApplicationContext(),
						"输入正确的检索条件！", Toast.LENGTH_LONG).show();
			}
			// ...
		}

		@Override
		public void onGetPermissionState(int iError) {
			if (iError == MKEvent.ERROR_PERMISSION_DENIED) {
				// 授权Key错误：
				// Toast.makeText(getInstance().getApplicationContext(),
				// "请在 DemoApplication.java文件输入正确的授权Key！",
				// Toast.LENGTH_LONG).show();
				lg.e("Application", " 请在 mBMapManager.init(strKey)输入正确的授权Key！");
				getInstance().m_bKeyRight = false;
			}
		}
	}

}
